/**
 * 人才管理-黑名单，列表页
 */
import React from 'react';
import moment from 'moment';
import { router, withRouter } from 'umi';
import { Input, Radio, Button, Form, Icon, DatePicker, Select } from 'antd';
import { useRequest } from '@/hooks';
import { Pagination } from '@/components';
import { getDict } from '@/utils/dataDictUtil';
import { isEqual } from 'lodash';
import { SelectPostExtra } from '@/pages/Recruitment/containers/select';
import styles from './index.less';
import { SEX } from '../dictionary';
import { BlackListCardTable } from './containers';
import { CustomSearch } from '../components';
import { getBlackList } from './service';

const toNumber = val => {
    if (val instanceof Array) {
        return val.map(toNumber);
    }
    return !val && val !== 0 ? undefined : Number(val);
};
const NUMBER_KEYS = ['pageNo', 'pageSize'];
const STRING_ARR_KEYS = ['resumeStages'];

function ResumeList({ form, location, onDataExchange, handleJumpDetail }) {
    const { query } = location;
    const { getFieldDecorator, setFieldsValue } = form;
    const [agreeTypeList, setAgreeTypeList] = React.useState([]); // 学历
    // 字典获取
    React.useEffect(() => {
        getDict('agreeType').then(ret => setAgreeTypeList(ret));
    }, []);
    const {
        applyPosition,
        blockStartTime,
        blockEndTime,
        talentName,
        name,
        talentSex,
        talentDegree,
        orderByField = ''
    } = query;
    // 需转换成数字、字符串数组、数字数组
    const specialQuery = React.useMemo(
        () => ({
            ...NUMBER_KEYS.reduce((pre, key) => ({ ...pre, [key]: toNumber(query[key]) }), {}),
            ...STRING_ARR_KEYS.reduce((pre, key) => {
                let next = query[key];
                if (!(next instanceof Array)) {
                    next = next ? [next] : [];
                }
                return { ...pre, [key]: next };
            }, {})
        }),
        [...[...NUMBER_KEYS, ...STRING_ARR_KEYS].map(item => query[item])]
    );
    const sourceCondition = {
        pageSize: 10,
        name,
        applyPosition,
        blockStartTime,
        blockEndTime,
        talentName,
        talentSex,
        talentDegree,
        orderByField,
        ...specialQuery
    };
    // 查询条件
    const condition = React.useMemo(
        () =>
            Object.keys(sourceCondition).reduce((ret, key) => {
                const item = sourceCondition[key];
                if (!item && item !== 0) {
                    return ret;
                }
                return {
                    ...ret,
                    [key]: item,
                    orderByField: orderByField.replace('end', ''),
                    orderByFieldActive: orderByField ? orderByField.split('|')[1] : undefined
                };
            }, {}),
        [...Object.values(sourceCondition)]
    );

    // 设置条件
    const setCondition = n => {
        history.push({ query: { ...query, ...n } });
    };
    // 查询
    const { data, loading, run } = useRequest(() => getBlackList(condition), {
        refreshDeps: [condition]
    });
    // 无刷新逻辑
    const [dataSource, setDataSource] = React.useState([]);
    React.useEffect(() => {
        setDataSource(data?.data?.rows || []);
    }, [data]);

    // 页签
    const [currTab, setCurrTab] = React.useState('1');
    // 高级搜索展开标识
    const [advanceFold, setAdvanceFold] = React.useState(true);

    /**
     * 获取表单数据
     */
    const getFormCondition = React.useCallback(async () => {
        let values = {};
        try {
            values = await form.validateFields();
            console.log(values);
            const { blockDate = [], ...rest } = values;
            values = { ...rest };
            if (blockDate.length) {
                values.blockStartTime = moment(blockDate[0]).format('YYYY-MM-DD 00:00:00');
                values.blockEndTime = moment(blockDate[1]).format('YYYY-MM-DD 23:59:59');
            } else {
                values.blockStartTime = null;
                values.blockEndTime = null;
            }
        } catch (error) {
            console.log(error);
        }
        return values;
    }, []);
    // 刷新
    const handleRefresh = React.useCallback(() => {
        run();
        onDataExchange();
    }, [run]);
    // 表格变化
    const handleTableChange = async (pagination, filters, sorter) => {
        const values = await getFormCondition();
        const { field, order } = sorter;
        const transfer = (key, item) => {
            const arrayKeys = ['resumeStages'];
            const next = arrayKeys.indexOf(key) === -1 ? item?.[0] || '' : item || [];
            return { [key]: next };
        };
        const con = Object.keys(filters).reduce(
            (ret, key) => {
                const item = filters[key];
                return { ...ret, ...transfer(key, item) };
            },
            { pageNo: 1, orderByField: order ? `${field}|${order}` : '' }
        );
        setCondition({ ...con, ...values });
    };
    // 点击查询
    const handleSearch = async () => {
        const values = await getFormCondition();
        const newPart = { ...values, pageNo: 1 };
        if (isEqual(query, { ...query, ...newPart })) {
            run();
        } else {
            setCondition(newPart);
        }
    };
    const renderSelect = ({ dict, ...rest }) => (
        <Select allowClear style={{ width: 190 }} placeholder="请选择" {...rest}>
            {dict.map(item => (
                <Select.Option key={item.value} value={item.value}>
                    {item.text}
                </Select.Option>
            ))}
        </Select>
    );
    // 高阶条件
    const renderAdvanceCon = () => {
        if (advanceFold) {
            return '';
        }
        const flag = currTab === '1';
        return (
            <div className={styles.advanceCon}>
                <Form.Item label="应聘岗位">
                    {getFieldDecorator('applyPosition', {
                        initialValue: sourceCondition.applyPosition
                    })(<SelectPostExtra style={{ width: 190 }} />)}
                </Form.Item>
                <Form.Item label="姓名">
                    {getFieldDecorator('talentName', {
                        initialValue: talentName
                    })(<Input placeholder="请输入" allowClear style={{ width: 190 }} />)}
                </Form.Item>
                {flag && (
                    <>
                        <Form.Item label="性别">
                            {getFieldDecorator('talentSex', {
                                initialValue: talentSex || undefined
                            })(renderSelect({ dict: SEX }))}
                        </Form.Item>
                        {flag && (
                            <Form.Item label="学历">
                                {getFieldDecorator('talentDegree', { initialValue: talentDegree || undefined })(
                                    renderSelect({ dict: agreeTypeList })
                                )}
                            </Form.Item>
                        )}
                    </>
                )}
                <Form.Item label="拉黑时间">
                    {getFieldDecorator('blockDate', {
                        initialValue:
                            blockStartTime && blockEndTime ? [moment(blockStartTime), moment(blockEndTime)] : undefined
                    })(
                        <DatePicker.RangePicker
                            ranges={{
                                本周: [moment().startOf('week'), moment().endOf('week')],
                                本月: [moment().startOf('month'), moment().endOf('month')],
                                本季度: [moment().startOf('quarter'), moment().endOf('quarter')]
                            }}
                        />
                    )}
                </Form.Item>
            </div>
        );
    };

    return (
        <>
            <Form layout="inline" autoComplete="off">
                <header className={styles.headerWrapper}>
                    <div className={styles.conditionWrapper}>
                        <Form.Item>
                            {form.getFieldDecorator('name', { initialValue: name })(
                                <CustomSearch
                                    onSearch={value => {
                                        if (!value && !query.name) return;
                                        setFieldsValue({ name: value });
                                        handleSearch();
                                    }}
                                />
                            )}
                        </Form.Item>
                        <a onClick={() => setAdvanceFold(val => !val)}>
                            高级搜索
                            <Icon type={advanceFold ? 'caret-down' : 'caret-up'} />
                        </a>
                        <Button type="primary" style={{ marginLeft: 12 }} onClick={handleSearch}>
                            搜索
                        </Button>
                    </div>
                    <div className={styles.extendWrapper}>
                        <Radio.Group defaultValue={currTab} size="middle" onChange={e => setCurrTab(e.target.value)}>
                            <Radio.Button value="1">
                                <i className="icon iconfont iconkuanliebiaoshitu1"></i>
                            </Radio.Button>
                            <Radio.Button value="2">
                                <i className="icon iconfont iconzhailiebiaoshitu1"></i>
                            </Radio.Button>
                        </Radio.Group>
                    </div>
                </header>
                {renderAdvanceCon()}
            </Form>
            <BlackListCardTable
                onJumpDetail={handleJumpDetail}
                condition={condition}
                loading={loading}
                dataSource={dataSource}
                onChange={handleTableChange}
                onRefresh={handleRefresh}
                currTab={currTab}
            />
            <Pagination
                current={sourceCondition.pageNo}
                pageSize={sourceCondition.pageSize}
                total={data?.data?.total}
                loading={loading}
                onChange={value => {
                    const { current, ...rest } = value;
                    setCondition({ ...rest, pageNo: current });
                }}
            />
        </>
    );
}

export default Form.create()(withRouter(ResumeList));
